<?php

namespace App\Services\MakeSeckillOrder;


use Carbon\Carbon;
use App\Models\User;
use App\Models\Order;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class CloseUnpaidSeckillOrder
{
	protected ?User $user = null;

	protected string $unpaidCacheId;

    protected ?GoldRecord $record = null;

	public function __construct($uid, $unpaidCacheId)
	{
		$user = User::find($uid);
		$this->user = $user ?? null;
		$this->unpaidCacheId = $unpaidCacheId;
		$this->order = Order::find(Redis::hGet($unpaidCacheId, 'order_id'));
	}

	protected function canBeClosed(): bool
	{
		$isPaying = Redis::hGet($this->unpaidCacheId, 'is_paying');
		$isPaid = Redis::hGet($this->unpaidCacheId, 'is_paid');
		$isClosed = Redis::hGet($this->unpaidCacheId, 'closed_at');

		if(!$this->order) return false;
		if ($isPaying) return false;
		if ($isPaid)  return false;
		if ($isClosed) return false;

		return true;
	}


	protected function restoreSelling()
	{
		//Redis::hMset($this->unpaidCacheId,['closed_at'=>Carbon::now()]);
		$this->order->update(['closed_at' => Carbon::now()]);
		$this->order->items->each(function ($item) {
				$item->sku->increaseStock($item->amount);
		});
		
		$this->user->closeOrderFromUnpaidCache($this->unpaidCacheId);
	}

	public function close()
	{
		if (!$this->user) return;

		if (! $this->canBeClosed()) return;

		$this->restoreSelling();
	}
}
